package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import org.elasticsearch.common.text.Text;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ItemClient itemClient;


    @Override
    public PageDTO<ItemDoc> searchList(RequestParams requestParams) {
        //1.构建SearchRequest对象
        SearchRequest searchRequest = new SearchRequest("item");
        //2.前端查询条件的封装
        buildBasicQuery(requestParams, searchRequest);
        //3.分页
        int page = requestParams.getPage();
        int size = requestParams.getSize();
        searchRequest.source().from((page - 1) * size).size(size);

        //4.发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //5.解析响应
        return handleResponse(response);
    }

    @Override
    public void deleteEs(String id) {
        DeleteRequest request = new DeleteRequest("item", id); //索引库名称
        try {
            DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveOrUpdateEs(String jsonString) {
        Item item = JSON.parseObject(jsonString, Item.class);
        ItemDoc itemDoc = new ItemDoc(item);

        IndexRequest request = new IndexRequest("item"); //索引库名称
        request.id(item.getId().toString());
        String jsonStr = JSON.toJSONString(itemDoc);
        request.source(jsonStr, XContentType.JSON);
        try {
            IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            buildBasicQuery(requestParams, request);
            request.source().size(0);   //设置数量
            buildAggregation(request);  //聚合
            // 3.发出请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 根据分类名称，获取分类结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            // 根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
    }

    private void buildBasicQuery(RequestParams params, SearchRequest searchRequest) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 3.商品分类条件
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("name", params.getCategory()));
        }
        // 4.商品品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 5.商品价格条件
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        // 6.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });

        // 7.放入source
        searchRequest.source().query(functionScoreQuery);
    }


    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        // 1.解析响应
        SearchHits searchHits = response.getHits();
        // 2.获取总条数
        long total = searchHits.getTotalHits().value;
        // 3.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.遍历
        List<ItemDoc> items = new ArrayList<>();
        for (SearchHit thisHit : hits) {
            // 获取文档source
            String json = thisHit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);

            //高亮显示
            Map<String, HighlightField> highlightFields = thisHit.getHighlightFields();
            if(highlightFields!=null){
                HighlightField highlightField = highlightFields.get("brand");
                if(highlightField!=null){
                    Text[] fragments = highlightField.fragments();
                    if(fragments!=null&&fragments.length>0){
                        itemDoc.setName(fragments[0].string());
                    }
                }
            }
            // 放入集合
            items.add(itemDoc);
        }

        // 5.封装返回
        return new PageDTO<>(total,items);
    }

}